﻿using System;
using System.Threading;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Collections.Concurrent;

namespace MDK.Common
{
    /// <summary>
    /// 任务队列
    /// </summary>
    public class TaskQueue
    {
        /// <summary>
        /// 安全队列
        /// </summary>
        private readonly static ConcurrentQueue<Func<Task>> taskQueues = new ConcurrentQueue<Func<Task>>();

        /// <summary>
        /// 锁
        /// </summary>
        private readonly static AutoResetEvent resetEvent = new AutoResetEvent(true);

        /// <summary>
        /// 实时检测任务
        /// </summary>
        public static void Work()
        {
            Task.Factory.StartNew(() => 
            {
                while (true)
                {
                    try
                    {
                        if (taskQueues.Count > 0)
                        {
                            //锁住
                            resetEvent.WaitOne();

                            Pop(); // 有任务时，出列任务
                        }
                    }
                    catch(Exception ex)
                    {

                    }
                }
            });
        }

        /// <summary>
        /// 任务入队
        /// </summary>
        /// <param name="task"></param>
        public static void Push(Func<Task> task)
        {
            taskQueues.Enqueue(task);
        }

        /// <summary>
        /// 任务出队
        /// </summary>
        private static void Pop()
        {
            Func<Task> currentTask;
            taskQueues.TryDequeue(out currentTask);

            if (currentTask != null)
                currentTask();
        }

        /// <summary>
        /// 释放锁
        /// </summary>
        public static void Set()
        {
            resetEvent.Set();
        }
    }
}
